import type { MultipleConditionSearchSchema } from '@/components/multiple-condition-search'
import { getApplicationsApi } from '@/apis/modules/application'
import {
  E_JOB_STATUS,
  jobProductOptions,
  jobStatusOptions,
  jobTypeOptions,
} from '@/enums/job'

export default function useConfig() {
  const appList = ref<LabelValue[]>([])

  async function getApplications() {
    const res = await getApplicationsApi({ limit: 500 })
    appList.value = (res.list || []).map((item) => {
      return {
        label: item.name!,
        value: item.app_id!,
      }
    })
  }

  const searchSchema = computed<MultipleConditionSearchSchema>(() => {
    return {
      placeholder: '默认按照订单号搜索',
      widgets: [
        {
          type: 'input',
          field: 'order_id',
          label: '订单号',
          maxLength: 20,
        },
        {
          type: 'select',
          field: 'app_id',
          label: '应用',
          options: appList.value,
        },
        {
          type: 'select',
          field: 'product',
          label: '产品',
          options: jobProductOptions,
        },
        {
          type: 'select',
          field: 'type',
          label: '任务内容',
          options: jobTypeOptions,
        },
        {
          type: 'select',
          field: 'status',
          label: '状态',
          options: jobStatusOptions,
        },
      ],
    }
  })

  const tableColumns = buildColumns([
    {
      title: '订单号',
      dataIndex: 'order_id',
      format: 'copy',
    },
    {
      title: '所属应用',
      dataIndex: 'app_id',
      render({ record }) {
        return getOptionLabel(record.app_id, appList.value)
      },
    },
    {
      title: '产品',
      dataIndex: 'product',
      render({ record }) {
        return getOptionLabel(record.job_product, jobProductOptions)
      },
    },
    {
      title: '任务内容',
      dataIndex: 'type',
      render({ record }) {
        return getOptionLabel(record.job_type, jobTypeOptions)
      },
    },
    {
      title: '开始时间',
      dataIndex: 'created_at',
      format: 'date-time',
      sortable: sortableSettings,
    },
    {
      title: '结束时间',
      dataIndex: 'updated_at',
      sortable: sortableSettings,
      render({ record }) {
        return record.status === E_JOB_STATUS.RUNNING
          ? '-'
          : formatDate(record.updated_at)
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      slotName: 'status',
    },
    {
      title: '操作',
      width: 70,
      slotName: 'actions',
      cellClass: 'actions-cell',
    },
  ])

  onMounted(getApplications)

  return {
    searchSchema,
    tableColumns,
  }
}
